package web.servlet;

import com.alibaba.fastjson.JSONObject;
import com.rdc.example.bean.Result;
import com.rdc.example.bean.dto.UserDTO;
import com.rdc.example.service.impl.UserServiceImpl;
import com.rdc.example.util.CheckCodeUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.rdc.example.util.FileUtil.uploadFile;


@WebServlet("/auto/*")
@MultipartConfig
public class AutoServlet extends BaseServlet {

    UserServiceImpl userService = new UserServiceImpl();

    public void login(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取数据
        request.setCharacterEncoding("UTF-8");
        String userName = request.getParameter("username");
        String password = request.getParameter("password");
        String remember = request.getParameter("remember");
        System.out.println("userName:"+userName+"  password:"+password);
        //验证数据
        Result result=userService.login(userName,password);
        boolean flag=(result.getCode()==200);
        // 设置响应类型为 JSON
        if(flag){
            //用户信息存入session
            HttpSession session=request.getSession();
            UserDTO userDTO=userService.getUserByUserName(userName);
            session.setAttribute("userDTO",userDTO);
            // 设置cookie
            if("true".equalsIgnoreCase(remember)){
                /* Tomcat7 cookie不能直接存中文，先编码存进去，再拿出来解码
                    URLEncoder.encode(name, "utf-8");
                    URLDecoder.decode(cookies[i].getName(),"utf-8") */
                Cookie userCookie = new Cookie("saved_username", URLEncoder.encode(userName, "utf-8"));
                Cookie passwordCookie = new Cookie("saved_password", URLEncoder.encode(password, "utf-8"));

                System.out.println(userCookie.getValue()+","+passwordCookie.getValue());
                userCookie.setPath("/");
                passwordCookie.setPath("/");
                // 7天
                int maxAge = 7 * 24 * 60 * 60;
                userCookie.setMaxAge(maxAge);
                passwordCookie.setMaxAge(maxAge);
                //发送cookie
                response.addCookie(userCookie);
                response.addCookie(passwordCookie);
            }else {
                // 清除可能存在的旧Cookie
                Arrays.asList("saved_username", "saved_password").forEach(name -> {
                    Cookie cookie = new Cookie(name, "");
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                });
            }
        }
        // 返回完整 JSON 数据（result）
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(JSONObject.toJSONString(result));
        System.out.println(result);
    }

//    private Cookie createExpiredCookie(String name) {
//        Cookie cookie = new Cookie(name, "");
//        cookie.setMaxAge(0);
//        cookie.setPath("/");
//        return cookie;
//    }

    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 清除session
        request.getSession().invalidate();
        // 清除Cookie
        Cookie[] cookies = request.getCookies();
        if(cookies != null) {
            for (Cookie cookie : cookies) {
                if(cookie.getName().startsWith("saved_")) {
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                }
            }
        }
        response.sendRedirect("login.html");
    }

    public void register(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取验证码
        System.out.println("register");
        //获取信息
        //response.setContentType("text/html;charset=utf-8");
        response.setContentType("application/json;charset=utf-8");
        //创建DiskFileItemFactory工厂对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //设置文件缓存目录，如果该文件夹不存在则创建一个
        File file = new File("D:\\TempFolder");
        if (!file.exists()) {
            file.mkdirs();
        }
        factory.setRepository(file);
        //创建ServletFileUpload对象
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        //设置字符编码
        fileUpload.setHeaderEncoding("utf-8");
        //解析request，获取FileItem对象
        List<FileItem> fileItems = fileUpload.parseRequest(request);
        //获取注册用户信息 使用map储存,再读出来
        Map<String, String> formFields = new HashMap<>();
        for (FileItem item : fileItems) {
            if (item.isFormField()) {
                formFields.put(item.getFieldName(), item.getString("UTF-8"));
            }
        }//map中读取数据
        String checkCode=formFields.get("checkCode");
        UserDTO userDTO=new UserDTO();
        userDTO.setUserName(formFields.get("username"));
        userDTO.setPassword(formFields.get("password"));
        userDTO.setPhone(formFields.get("phone"));
        userDTO.setEmail(formFields.get("email"));
        //检验密码
        if(userDTO.getPassword().length()<6||userDTO.getPassword().length()>15){
            response.getWriter().write(JSONObject.toJSONString(Result.fail("密码必须在6到15位",null)));
            return;
        }
        //检验重名
        if(userService.checkUserName(userDTO.getUserName())){
            response.getWriter().write(JSONObject.toJSONString(Result.fail("用户名称已存在",null)));
            return;
        }
        //在session中获取生成的验证码
        HttpSession session = request.getSession();
        String checkCodeGen= (String) session.getAttribute("checkCodeGen");
        if(!checkCodeGen.equals(checkCode)){
            //验证码不对
            response.getWriter().write(JSONObject.toJSONString(Result.fail("验证码错误",null)));
            return;
        }
        Result result=userService.insertUser(userDTO,fileItems);
        if (result.getCode()==200) {
            //注册成功 用户信息存入session
            userDTO=userService.getUserByUserName(userDTO.getUserName());
            session.setAttribute("userDTO",userDTO);
        }
        //返回结果
        response.getWriter().write(JSONObject.toJSONString(result));
    }


    public void checkName(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //检查名字是否重复
        request.setCharacterEncoding("UTF-8");
        String username = request.getParameter("username");
        //调用service查询
        boolean flag= userService.checkUserName(username);
        //返回结果
        response.getWriter().write(""+flag);
    }



    public void checkCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        //checkCode 是生成的验证码
        ServletOutputStream os = response.getOutputStream();
        String checkCode = CheckCodeUtil.outputVerifyImage(100, 50, os, 4);
        //生成的验证码存入session
        System.out.println("生成的验证码:"+checkCode);

        session.setAttribute( "checkCodeGen",checkCode);
    }

    public void sendEmail(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("sendEmail...");
        request.setCharacterEncoding("UTF-8");
        String userName = request.getParameter("username");
        Result result=userService.setCodeToEmail(userName);
        if (result.getCode()==200) {
            //发送成功 发送的邮箱验证码存入session
            HttpSession session=request.getSession();
            String emailCode=(String) result.getData();
            session.setAttribute("emailCode",emailCode);
        }
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSONObject.toJSONString(result));
    }

    public void updatePassword(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("updatePassword...");
        request.setCharacterEncoding("UTF-8");
        String userName = request.getParameter("username");
        String password = request.getParameter("password");
        String emailCode = request.getParameter("emailCode");
        //从session获取emailCode
        HttpSession session = request.getSession();
        String emailCodeGen = (String) session.getAttribute("emailCode");
        //检验密码长度 6-15
        response.setContentType("application/json;charset=utf-8");
        if(password.length()<6||password.length()>15){
            response.getWriter().write(JSONObject.toJSONString(Result.fail("密码必须在6到15位",null)));
            return;
        }
        //检测邮箱验证码是不是一样
        if (!emailCode.equals(emailCodeGen)) {
            response.getWriter().write(JSONObject.toJSONString(Result.fail("邮箱验证码错误",null)));
            return;
        }
        Result result=userService.updatePassword(userName,password);
        if (result.getCode()==200) {
            //更新成功，清除emailCode
            session.removeAttribute("emailCode");
        }
        response.getWriter().write(JSONObject.toJSONString(result));
    }

}
